package vehicle

import (
	"fmt"
	"server/util"
)

type VehicleLogic struct {
	dao *VehicleDao
}

func NewVehicleLogic() *VehicleLogic {
	return &VehicleLogic{
		dao: NewVehicleDao(),
	}
}
func (v *VehicleLogic) GetVehicleInfo(userId string, vtId int64) (Vehicle, error) {
	return v.dao.getVehicleInfo(userId, vtId)
}
func (v *VehicleLogic) GetVehicleList(userId string) ([]Vehicle, error) {
	return v.dao.getVehiclList(userId)
}
func (v *VehicleLogic) UpdateLevel(userId string, vtId, step int64) ([]Vehicle, error) {
	vehicleInfo, err := v.dao.getVehicleInfo(userId, vtId)
	if err != nil {
		return nil, fmt.Errorf("不要下请求s")
	}
	vehicleInfo.Level += step
	err = v.dao.updateLevel(userId, vtId, vehicleInfo.Level)
	if err != nil {
		return nil, fmt.Errorf("升级失败")
	}
	ret, err := v.dao.getVehiclList(userId)
	return ret, nil

}
func (v *VehicleLogic) DestroyCar(userId string, vtId int64) error {
	_, err := v.dao.getVehicleInfo(userId, vtId)
	if err != nil {
		return fmt.Errorf("没有该")
	}
	return v.dao.removeCar(userId, vtId)
}
func (v *VehicleLogic) UnLockSkillInfo(userId string, vtId int64, skillId int32) ([]Vehicle, error) {
	vehicleInfo, err := v.dao.getVehicleInfo(userId, vtId)
	if err != nil {
		return nil, fmt.Errorf("不要下请求s")
	}
	newSkillInfo := SkillInfo{
		SkillId: skillId,
	}
	vehicleInfo.SkillList = append(vehicleInfo.SkillList, newSkillInfo)
	err = v.dao.updateSkill(userId, vtId, vehicleInfo.SkillList)
	if err != nil {
		return nil, err
	}
	ret, err := v.dao.getVehiclList(userId)
	return ret, nil
}

func (v *VehicleLogic) NewVehicle(userId string, vtId int64) ([]Vehicle, error) {
	newVehicleInfo := Vehicle{
		UserId:    userId,
		VTId:      vtId,
		Level:     1,
		SkillList: make([]SkillInfo, 0),
	}
	err := v.dao.insert(userId, newVehicleInfo)
	if err != nil {
		return nil, err
	}
	ret, err := v.dao.getVehiclList(userId)
	return ret, nil
}
func (v *VehicleLogic) RandNum(userId string, vtId int64, skillId int32) ([]Vehicle, error) {
	vehicleInfo, err := v.dao.getVehicleInfo(userId, vtId)
	if err != nil {
		return nil, fmt.Errorf("不要下请求s")
	}
	for key, skillInfo := range vehicleInfo.SkillList {
		if skillInfo.SkillId == skillId {
			vehicleInfo.SkillList[key].Offect = util.GetRandomInt(0, 30)
		}
	}
	err = v.dao.updateSkill(userId, vtId, vehicleInfo.SkillList)
	if err != nil {
		return nil, err
	}
	return v.dao.getVehiclList(userId)

}
func (v *VehicleLogic) UpdateSkillLevel(userId string, vtId int64, skillId int32) ([]Vehicle, error) {
	vehicleInfo, err := v.dao.getVehicleInfo(userId, vtId)
	if err != nil {
		return nil, fmt.Errorf("不要下请求s")
	}
	for key, skillInfo := range vehicleInfo.SkillList {
		if skillInfo.SkillId == skillId {
			vehicleInfo.SkillList[key].Level++
		}
	}
	err = v.dao.updateSkill(userId, vtId, vehicleInfo.SkillList)
	if err != nil {
		return nil, err
	}
	return v.dao.getVehiclList(userId)
}
